public class TestDemo {
    public static void main(String[] args) {
        String s="hello";
        s+=" world";
        //这个操作不是在修改“hello”，而是创建了一个新的字符串对象“hello world”给了s
        System.out.println(s);


        //Java中也提供了可变字符串，StringBuffer和StringBuilder
        StringBuilder stringBuilder=new StringBuilder("hello");
        stringBuilder.append(" world");
        //这个操作时操作stringBuilder的对象本体，而没有创建新的对象
        System.out.println(stringBuilder.toString());
        System.out.println(stringBuilder);


        String s1="";
        int loopCount=10_0000;
        long startTime=System.currentTimeMillis();//获取毫秒级别的时间戳
        for (int i = 0; i < loopCount; i++) {
            s+=i;
        }
        long endTime=System.currentTimeMillis();
        System.out.println("时间：" + (endTime - startTime));//2214
        //每次进入循坏都要创建一个新的对象，出循环又要销毁，所以时间长
        StringBuilder stringBuilder1=new StringBuilder("");
        long startTime1=System.currentTimeMillis();
        for (int i = 0; i < loopCount; i++) {
            stringBuilder1.append(i);
        }
        long endTime1=System.currentTimeMillis();
        System.out.println("时间：" + (endTime1 - startTime1));//2


        //扩容（Java中会自动扩容的）
        StringBuilder stringBuilder2=new StringBuilder("hello");
        System.out.println(stringBuilder2.capacity());//21
        stringBuilder2.ensureCapacity(128);
        System.out.println(stringBuilder2.capacity());//128
        stringBuilder2.setCharAt(1,'x');//将1位置的设置成‘x’
        System.out.println(stringBuilder2);//hxllo
        stringBuilder2.delete(1,3);//删除【1,3）
        System.out.println(stringBuilder2);//hlo
        stringBuilder2.replace(1,3,"xxx");//和String不同，这个是直接修改对象本体，将1,2变为xxx
        System.out.println(stringBuilder2);//hxxx
        stringBuilder2.reverse();//字符串的逆序，修改对象本身
        System.out.println(stringBuilder2);//xxxh



    }
}
